<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class ExchangeGoods extends BaseModel
{
    use HasFactory;
    protected $table = 'exchange_goods';
    // 允许批量操作的字段
    protected $fillable = ['order_id','exchange_time','remark','is_del','num','semi_id_now','semi_id','finish_id','created_at','updated_at'];
    public function scopeSearch($query,$params)
    {
        //客户
        if(!empty($params['customer_id'])){
            $order_id = Order::where('customer_id',$params['customer_id'])->pluck('id')->toArray();
            $query->whereIn('order_id',$order_id);
        }
        //订单号
        if(!empty($params['order_number'])){
            $order_id = Order::where('order_number',$params['order_number'])->value('id');
            $query->where('order_id',$order_id);
        }

        //产品
        if(!empty($params['product_id'])){
            $order_ids = Order::where('product_id',$params['product_id'])->pluck('id')->toArray();
            $query->whereIn('order_id',$order_ids);
        }
        //型号
        if(!empty($params['model_number_id'])){
            $order_ids = Order::where('model_number_id',$params['model_number_id'])->pluck('id')->toArray();
            $query->whereIn('order_id',$order_ids);
        }
        //流水号
        if(!empty($params['serial_number'])){
            $order_id = Order::where('serial_number',$params['serial_number'])->value('id');
            $query->where('order_id',$order_id);
        }
        $query->where('is_del',2);
    }

    public function order(){
        return $this->hasOne(Order::class,'id','order_id')
            ->with([
                'color',
                'product_name'=>function($q){
                    return $q->select('id','product_name');
                },
                'customer'=>function($q){
                    return $q->select('id','customer_name','customer_address','contact_phone');
                },
                'model_number_name',
                'specification'
            ])
            ->select('order.id','order.color_id','order.product_id',
                'order.customer_id','order.model_number_id','order.specification_id',
                'order.batch_number','order.remark','order.order_number','order.serial_number');
    }
    public function semi(){
        return $this->hasOne(SemiFinishProduct::class,'id','semi_id');
    }

}
